﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Drawing.Drawing2D;
using System.IO.Ports;
using SerialPortHelperLib;
using XChipTool.Enties;
using System.Runtime.InteropServices;
using System.Configuration;
using XChip_Common;
using BinAnalysisHelp;
using AdbService;

namespace XChipTool
{
    public partial class XChip_HDR : DevExpress.XtraEditors.XtraUserControl
    {

        #region 全局变量
        addressregisterManager addrDal;
        //串口
        public SerialPort sPortTemp;
        //是否在获取数据
        private bool isRead = false;
        private bool isWrite = false;
        List<addressregister> hdrList = new List<addressregister>();

        private addressregisterManager aBll;
        //记录是否使用USB设备读写
        public bool IsUsbOpen = false;
        //记录是否使用I2C设备读写
        public bool m_open = false;

        private List<addressregister> XChipHDR;

        private XChip_HDR_Ae xChip_HDR_Ae;

        private static XChip_HDR _instance;


        // 使用服务定位器获取ADB服务
        private IAdbCommandService adbService = ServiceLocator.AdbCommandService;

        public static XChip_HDR Instance(SerialPort _sPortTemp, addressregisterManager _aBll)
        {
            if (_instance == null)
            {
                _instance = new XChip_HDR(_sPortTemp, _aBll);
            }
            return _instance;
        }
        #endregion
        public XChip_HDR()
        {

            InitializeComponent();
        }
        public XChip_HDR(SerialPort _sPortTemp, addressregisterManager _aBll)
        {
            sPortTemp = _sPortTemp;
            aBll = _aBll;
            XChipHDR = aBll.GetList(c => c.ChipType == ConfigurationManager.AppSettings["xc151_ChipType"] && (c.Classify == "HDR"));
            InitializeComponent();

        }

        private async void CheckMethod()
        {
            #region 勾选框获取
            //combine mode 0:normal mode; 1:sensor combine mode; 2:2 frame combine mode; 3:3 frame combine mode  
            var combine = GetRegister("combine_mode_en", hdrList);
            //if (combine == 0x80)
            //{
            //    combineRadio.SelectedIndex = 0;
            //}
            //else
            //{
            //    combineRadio.SelectedIndex = 1;
            //}
            //combineRadio.SelectedIndex = (int)((combine >> 6) & 0x03);

            //if (((combine>>6)&0x03)==0)
            //{

            //}
            //else if (((combine >> 6) & 0x03) == 1)
            //{

            //}
            //else if (((combine >> 6) & 0x03) == 2)
            //{

            //}
            //else if (((combine >> 6) & 0x03) == 3)
            //{

            //}


            //Scene_Recognition_en
            //if (((SerialSend.ReadRegister((Convert.ToUInt32(hdrList.Where(c => c.NameType == "scene_recognition").First().Address, 16)), sPortTemp)) & 0x01) == 1)
            //{
            //    Scene_Recognition_en.CheckState = CheckState.Checked;
            //}
            //else
            //{
            //    Scene_Recognition_en.CheckState = CheckState.Unchecked;
            //}
            //Decowprssion_en [4]


            //Log_Combine_en [0]

            //Compression_en [5]
            if (((await(GetRegister("compression_in_en", hdrList)) >> 5) & 0x01) == 1)
            {
                Compression_en.CheckState = CheckState.Checked;
            }
            else
            {
                Compression_en.CheckState = CheckState.Unchecked;
            }
            //YUV_Gamma_en
            //if (((SerialSend.ReadRegister((Convert.ToUInt32(hdrList.Where(c => c.NameType == "yuv_gamma").First().Address, 16)), sPortTemp)) & 0x01) == 1)
            //{
            //    YUV_Gamma_en.CheckState = CheckState.Checked;
            //}
            //else
            //{
            //    YUV_Gamma_en.CheckState = CheckState.Unchecked;
            //}

            //Log_Gamma_en [3]
            if (((await (GetRegister("Log_Gamma_en", hdrList)) >> 3) & 0x01) == 1)
            {
                Log_Gamma_en.CheckState = CheckState.Checked;
            }
            else
            {
                Log_Gamma_en.CheckState = CheckState.Unchecked;
            }

            //Normalize_en
            if (((await (GetRegister("Normalize_en", hdrList)) >> 6) & 0x01) == 1)
            {
                Normalize_en.CheckState = CheckState.Checked;
            }
            else
            {
                Normalize_en.CheckState = CheckState.Unchecked;
            }

            //Gamma_Correetion_en [2]
            if (((await (GetRegister("gamma_correction", hdrList)) >> 2) & 0x01) == 1)
            {
                Gamma_Correetion_en.CheckState = CheckState.Checked;
            }
            else
            {
                Gamma_Correetion_en.CheckState = CheckState.Unchecked;
            }



            //single_frames

            //continuous frames


            #endregion
        }

        private async Task<long> GetRegister(string NType, List<addressregister> list)
        {
            long getTemp = -1;
            var ntList = list.Where(c => c.NameType.ToLower().Contains(NType.ToLower())).OrderBy(c => c.Sorting).ToList();
            switch (ntList.Count())
            {
                case 1:
                    
                 getTemp = (await ReadRegisterAsync(ntList[0].Address));
                    break;
                case 2:
                    {
                        var nHigh = await ReadRegisterAsync(ntList[0].Address);
                        var nLow = await ReadRegisterAsync(ntList[1].Address);
                        getTemp = (nHigh << 8 & 0xff00) | (nLow & 0xff);
                    }
                    break;
                case 3:
                    {
                        var nHigh = await ReadRegisterAsync(ntList[0].Address);
                        var nMiddle = await ReadRegisterAsync(ntList[1].Address);
                        var nLow = await ReadRegisterAsync(ntList[2].Address);
                        getTemp = (nHigh << 16 & 0xff0000) | ((nMiddle << 8 & 0xff00)) | (nLow & 0xff);
                    }
                    break;
                default:
                    break;
            }
            return getTemp;
        }
        private async Task<long> GetRegister(string nameType)
        {

          

            if (XChipHDR.Exists(c => c.NameType.ToLower() == nameType.ToLower()))
            {
                long var = await ReadRegisterAsync(XChipHDR.Where(c => c.NameType.ToLower() == nameType.ToLower()).First().Address);
                return var;
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($"未找到{nameType}"); return -1;
            }
        }
        private async void SetRegister(string NType, ulong add, List<addressregister> list)
        {
            var ntList = list.Where(c => c.NameType.ToLower().Contains(NType.ToLower())).OrderBy(c => c.Sorting).ToList();
            if (IsUsbOpen)
            {
                bool isbool;
                uint addrstr;
                switch (ntList.Count())
                {
                    case 1:

                        if (IntPtr.Size == 8)
                        {
                            isbool = XChipUSB.UsbRegisterWrite64((uint)Convert.ToUInt32(ntList[0].Address, 16), (uint)add, false);
                        }
                        else
                        {
                            isbool = XChipUSB.UsbRegisterWrite86((uint)Convert.ToUInt32(ntList[0].Address, 16), (uint)add, false);
                        }
                        addrstr = Convert.ToUInt32(ntList[0].Address, 16);
                        SerialSend.Sendser("W:0x" + addrstr.ToString("X2"), add.ToString("X2"));
                        //SerialSend.WriteRegister(0x21, Convert.ToUInt32(ntList[0].Address, 16), add, sPortTemp);
                        if (null != BinHelp.usbList)
                        {
                            uint pVule = 0x0;
                            isbool = false;
                            if (IntPtr.Size == 8)
                            {
                                isbool = XChipUSB.UsbRegisterRead64(BinHelp.CurrentSize, ref pVule, true);
                                SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));


                            }
                            else
                            {
                                isbool = XChipUSB.UsbRegisterRead86(BinHelp.CurrentSize, ref pVule, true);
                                SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));
                            }
                            var chang = (int)(pVule >> 16); // 使用右移16位操作来获取高16位  
                            var kuang = (int)(pVule & 0xFFFF); // 使用位与操作来获取低16位  

                            BinHelp.SstBinUsbUpdateData(ref BinHelp.BinList, ntList[0].Address, add.ToString("X"), chang, kuang);
                        }
                        break;
                    case 2:
                        {
                            if (NType.ToLower().Contains("node_list") && ((add >> 8) & 0xff) > 0x1f)
                            {

                                if (IntPtr.Size == 8)
                                {
                                    isbool = XChipUSB.UsbRegisterWrite64((uint)Convert.ToUInt32(ntList[0].Address, 16), (uint)0x1f, false);
                                }
                                else
                                {
                                    isbool = XChipUSB.UsbRegisterWrite86((uint)Convert.ToUInt32(ntList[0].Address, 16), (uint)0x1f, false);
                                }
                                addrstr = Convert.ToUInt32(ntList[0].Address, 16);
                                SerialSend.Sendser("W:0x" + addrstr.ToString("X2"), 0x1f.ToString("X2"));
                                if (null != BinHelp.usbList)
                                {
                                    uint pVule = 0x0;
                                    isbool = false;
                                    if (IntPtr.Size == 8)
                                    {
                                        isbool = XChipUSB.UsbRegisterRead64(BinHelp.CurrentSize, ref pVule, true);
                                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));


                                    }
                                    else
                                    {
                                        isbool = XChipUSB.UsbRegisterRead86(BinHelp.CurrentSize, ref pVule, true);
                                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));
                                    }
                                    var chang = (int)(pVule >> 16); // 使用右移16位操作来获取高16位  
                                    var kuang = (int)(pVule & 0xFFFF); // 使用位与操作来获取低16位  

                                    BinHelp.SstBinUsbUpdateData(ref BinHelp.BinList, ntList[0].Address, (0x1f).ToString("X"), chang, kuang);
                                }
                            }
                            else
                            {
                                if (IntPtr.Size == 8)
                                {
                                    isbool = XChipUSB.UsbRegisterWrite64((uint)Convert.ToUInt32(ntList[0].Address, 16), (uint)((add >> 8) & 0xff), false);
                                }
                                else
                                {
                                    isbool = XChipUSB.UsbRegisterWrite86((uint)Convert.ToUInt32(ntList[0].Address, 16), (uint)((add >> 8) & 0xff), false);
                                }
                                addrstr = Convert.ToUInt32(ntList[0].Address, 16);
                                SerialSend.Sendser("W:0x" + addrstr.ToString("X2"), ((add >> 8) & 0xff).ToString("X2"));
                                if (null != BinHelp.usbList)
                                {
                                    uint pVule = 0x0;
                                    isbool = false;
                                    if (IntPtr.Size == 8)
                                    {
                                        isbool = XChipUSB.UsbRegisterRead64(BinHelp.CurrentSize, ref pVule, true);
                                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));


                                    }
                                    else
                                    {
                                        isbool = XChipUSB.UsbRegisterRead86(BinHelp.CurrentSize, ref pVule, true);
                                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));
                                    }
                                    var chang = (int)(pVule >> 16); // 使用右移16位操作来获取高16位  
                                    var kuang = (int)(pVule & 0xFFFF); // 使用位与操作来获取低16位  

                                    BinHelp.SstBinUsbUpdateData(ref BinHelp.BinList, ntList[0].Address, ((add >> 8) & 0xff).ToString("X"), chang, kuang);
                                }

                            }
                            if (NType.ToLower().Contains("gain_list") && ((add >> 8) & 0xff) > 0x03)
                            {
                                if (IntPtr.Size == 8)
                                {
                                    isbool = XChipUSB.UsbRegisterWrite64((uint)Convert.ToUInt32(ntList[0].Address, 16), (uint)0x03, false);
                                }
                                else
                                {
                                    isbool = XChipUSB.UsbRegisterWrite86((uint)Convert.ToUInt32(ntList[0].Address, 16), (uint)0x03, false);
                                }
                                addrstr = Convert.ToUInt32(ntList[0].Address, 16);
                                SerialSend.Sendser("W:0x" + addrstr.ToString("X2"), 0x03.ToString("X2"));
                                //SerialSend.WriteRegister(0x21, Convert.ToUInt32(ntList[0].Address, 16), 0x03, sPortTemp);
                                if (null != BinHelp.usbList)
                                {
                                    uint pVule = 0x0;
                                    isbool = false;
                                    if (IntPtr.Size == 8)
                                    {
                                        isbool = XChipUSB.UsbRegisterRead64(BinHelp.CurrentSize, ref pVule, true);
                                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));


                                    }
                                    else
                                    {
                                        isbool = XChipUSB.UsbRegisterRead86(BinHelp.CurrentSize, ref pVule, true);
                                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));
                                    }
                                    var chang = (int)(pVule >> 16); // 使用右移16位操作来获取高16位  
                                    var kuang = (int)(pVule & 0xFFFF); // 使用位与操作来获取低16位  

                                    BinHelp.SstBinUsbUpdateData(ref BinHelp.BinList, ntList[0].Address, (0x03).ToString("X"), chang, kuang);
                                }
                            }
                            else
                            {
                                if (IntPtr.Size == 8)
                                {
                                    isbool = XChipUSB.UsbRegisterWrite64((uint)Convert.ToUInt32(ntList[0].Address, 16), (uint)((add >> 8) & 0xff), false);
                                }
                                else
                                {
                                    isbool = XChipUSB.UsbRegisterWrite86((uint)Convert.ToUInt32(ntList[0].Address, 16), (uint)((add >> 8) & 0xff), false);
                                }
                                addrstr = Convert.ToUInt32(ntList[0].Address, 16);
                                SerialSend.Sendser("W:0x" + addrstr.ToString("X2"), ((add >> 8) & 0xff).ToString("X2"));
                                //SerialSend.WriteRegister(0x21, Convert.ToUInt32(ntList[0].Address, 16), (add >> 8) & 0xff, sPortTemp);
                                if (null != BinHelp.usbList)
                                {
                                    uint pVule = 0x0;
                                    isbool = false;
                                    if (IntPtr.Size == 8)
                                    {
                                        isbool = XChipUSB.UsbRegisterRead64(BinHelp.CurrentSize, ref pVule, true);
                                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));


                                    }
                                    else
                                    {
                                        isbool = XChipUSB.UsbRegisterRead86(BinHelp.CurrentSize, ref pVule, true);
                                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));
                                    }
                                    var chang = (int)(pVule >> 16); // 使用右移16位操作来获取高16位  
                                    var kuang = (int)(pVule & 0xFFFF); // 使用位与操作来获取低16位  

                                    BinHelp.SstBinUsbUpdateData(ref BinHelp.BinList, ntList[0].Address, ((add >> 8) & 0xff).ToString("X"), chang, kuang);
                                }
                            }
                            if (IntPtr.Size == 8)
                            {
                                isbool = XChipUSB.UsbRegisterWrite64((uint)Convert.ToUInt32(ntList[1].Address, 16), (uint)(add & 0xff), false);
                            }
                            else
                            {
                                isbool = XChipUSB.UsbRegisterWrite86((uint)Convert.ToUInt32(ntList[1].Address, 16), (uint)(add & 0xff), false);
                            }
                            addrstr = Convert.ToUInt32(ntList[1].Address, 16);
                            SerialSend.Sendser("W:0x" + addrstr.ToString("X2"), (add & 0xff).ToString("X2"));
                            //SerialSend.WriteRegister(0x21, Convert.ToUInt32(ntList[1].Address, 16), add & 0xff, sPortTemp);
                            if (null != BinHelp.usbList)
                            {
                                uint pVule = 0x0;
                                isbool = false;
                                if (IntPtr.Size == 8)
                                {
                                    isbool = XChipUSB.UsbRegisterRead64(BinHelp.CurrentSize, ref pVule, true);
                                    SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));


                                }
                                else
                                {
                                    isbool = XChipUSB.UsbRegisterRead86(BinHelp.CurrentSize, ref pVule, true);
                                    SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));
                                }
                                var chang = (int)(pVule >> 16); // 使用右移16位操作来获取高16位  
                                var kuang = (int)(pVule & 0xFFFF); // 使用位与操作来获取低16位  

                                BinHelp.SstBinUsbUpdateData(ref BinHelp.BinList, ntList[1].Address, (add & 0xff).ToString("X"), chang, kuang);
                            }

                        }
                        break;
                    case 3:
                        {
                            if (IntPtr.Size == 8)
                            {
                                isbool = XChipUSB.UsbRegisterWrite64((uint)Convert.ToUInt32(ntList[2].Address, 16), (uint)(add & 0xff), false);
                                isbool = XChipUSB.UsbRegisterWrite64((uint)Convert.ToUInt32(ntList[1].Address, 16), (uint)((add >> 8) & 0xff), false);
                                isbool = XChipUSB.UsbRegisterWrite64((uint)Convert.ToUInt32(ntList[0].Address, 16), (uint)((add >> 16) & 0xff), false);
                            }
                            else
                            {
                                isbool = XChipUSB.UsbRegisterWrite86((uint)Convert.ToUInt32(ntList[2].Address, 16), (uint)(add & 0xff), false);
                                isbool = XChipUSB.UsbRegisterWrite86((uint)Convert.ToUInt32(ntList[1].Address, 16), (uint)((add >> 8) & 0xff), false);
                                isbool = XChipUSB.UsbRegisterWrite86((uint)Convert.ToUInt32(ntList[0].Address, 16), (uint)((add >> 16) & 0xff), false);
                            }
                            addrstr = Convert.ToUInt32(ntList[2].Address, 16);
                            SerialSend.Sendser("W:0x" + addrstr.ToString("X2"), (add & 0xff).ToString("X2"));
                            addrstr = Convert.ToUInt32(ntList[1].Address, 16);
                            SerialSend.Sendser("W:0x" + addrstr.ToString("X2"), ((add >> 8) & 0xff).ToString("X2"));
                            addrstr = Convert.ToUInt32(ntList[0].Address, 16);
                            SerialSend.Sendser("W:0x" + addrstr.ToString("X2"), ((add >> 16) & 0xff).ToString("X2"));
                            //SerialSend.WriteRegister(0x21, Convert.ToUInt32(ntList[2].Address, 16), add & 0xff, sPortTemp);
                            //SerialSend.WriteRegister(0x21, Convert.ToUInt32(ntList[1].Address, 16), (add >> 8) & 0xff, sPortTemp);
                            //SerialSend.WriteRegister(0x21, Convert.ToUInt32(ntList[0].Address, 16), (add >> 16) & 0xff, sPortTemp);
                            if (null != BinHelp.usbList)
                            {
                                uint pVule = 0x0;
                                isbool = false;
                                if (IntPtr.Size == 8)
                                {
                                    isbool = XChipUSB.UsbRegisterRead64(BinHelp.CurrentSize, ref pVule, true);
                                    SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));


                                }
                                else
                                {
                                    isbool = XChipUSB.UsbRegisterRead86(BinHelp.CurrentSize, ref pVule, true);
                                    SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));
                                }
                                var chang = (int)(pVule >> 16); // 使用右移16位操作来获取高16位  
                                var kuang = (int)(pVule & 0xFFFF); // 使用位与操作来获取低16位  

                                BinHelp.SstBinUsbUpdateData(ref BinHelp.BinList, ntList[2].Address, (add & 0xff).ToString("X"), chang, kuang);
                                BinHelp.SstBinUsbUpdateData(ref BinHelp.BinList, ntList[1].Address, ((add >> 8) & 0xff).ToString("X"), chang, kuang);
                                BinHelp.SstBinUsbUpdateData(ref BinHelp.BinList, ntList[0].Address, ((add >> 16) & 0xff).ToString("X"), chang, kuang);
                            }
                        }
                        break;
                    default:
                        break;
                }
            }
            else
            {
                switch (ntList.Count())
                {
                    case 1:
                        SerialSend.WriteRegister(Convert.ToUInt32(ntList[0].Address, 16), add, sPortTemp);
                       
                        break;
                    case 2:
                        {
                            if (NType.ToLower().Contains("node_list") && ((add >> 8) & 0xff) > 0x1f)
                            {
                                SerialSend.WriteRegister(Convert.ToUInt32(ntList[0].Address, 16), 0x1f, sPortTemp);
                               
                            }
                            else
                            {
                                SerialSend.WriteRegister(Convert.ToUInt32(ntList[0].Address, 16), (add >> 8) & 0xff, sPortTemp);
                               
                            }
                            if (NType.ToLower().Contains("gain_list") && ((add >> 8) & 0xff) > 0x03)
                            {
                                SerialSend.WriteRegister(Convert.ToUInt32(ntList[0].Address, 16), 0x03, sPortTemp);
                                
                            }
                            else
                            {
                                SerialSend.WriteRegister(Convert.ToUInt32(ntList[0].Address, 16), (add >> 8) & 0xff, sPortTemp);
                                
                            }
                            SerialSend.WriteRegister(Convert.ToUInt32(ntList[1].Address, 16), add & 0xff, sPortTemp);
                            

                        }
                        break;
                    case 3:
                        {
                            SerialSend.WriteRegister(Convert.ToUInt32(ntList[2].Address, 16), add & 0xff, sPortTemp);
                            SerialSend.WriteRegister(Convert.ToUInt32(ntList[1].Address, 16), (add >> 8) & 0xff, sPortTemp);
                            SerialSend.WriteRegister(Convert.ToUInt32(ntList[0].Address, 16), (add >> 16) & 0xff, sPortTemp);
                            
                        }
                        break;
                    default:
                        break;
                }
            }

        }


        #region hdr1 文本和勾选框设置值


        private async void Compression_en_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            if (hdrList.Count == 0)
            {
                if (null == addrDal)
                {
                    addrDal = new addressregisterManager();
                }
                hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
            }
            var readVal =await GetRegister("compression_in_en", hdrList); //[5]
            var addr = Compression_en.Checked ? readVal | 0x20 : readVal & 0xdf;
            SetRegister("compression_in_en", (ulong)addr, hdrList);
        }



        private async void Log_Gamma_en_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            if (hdrList.Count == 0)
            {
                if (null == addrDal)
                {
                    addrDal = new addressregisterManager();
                }
                hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
            }
            var readVal =await GetRegister("Log_Gamma_en", hdrList); //[3]
            var addr = Log_Gamma_en.Checked ? readVal | 0x08 : readVal & 0xf7;
            SetRegister("Log_Gamma_en", (ulong)addr, hdrList);
        }


        private async void Normalize_en_CheckedChanged(object sender, EventArgs e)
        {
            //if (isRead) return;
            //if (hdrList.Count == 0)
            //{
            //    if (null == addrDal)
            //    {
            //        addrDal = new addressregisterManager();
            //    }
            //    hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
            //}
            //var readVal = GetRegister("Normalize_en", hdrList); //[6]
            //var addr = Normalize_en.Checked ? readVal | 0x40 : readVal & 0xbf;
            //SetRegister("Normalize_en", (ulong)addr, hdrList);
            var chk = sender as CheckEdit;
            if (isRead) return;
            if (XChipHDR.Exists(c => c.NameType.ToLower() == (chk.Name).ToLower()))
            {
                var model = XChipHDR.Find(c => c.NameType.ToLower() == (chk.Name).ToLower());
                var Add = await ReadRegisterAsync(model.Address);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), chk.Checked);
                await SetHDRRegister(model, Val);
            }
        }

        private async void Gamma_Correetion_en_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            if (hdrList.Count == 0)
            {
                if (null == addrDal)
                {
                    addrDal = new addressregisterManager();
                }
                hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
            }
            var readVal =await GetRegister("gamma_correction", hdrList); //[2]
            var addr = Gamma_Correetion_en.Checked ? readVal | 0x4 : readVal & 0xfb;
            SetRegister("gamma_correction", (ulong)addr, hdrList);
        }



        #endregion
        #region hdr2 设置文本框值

        private void comb_thr_L0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                //if (hdrList.Count == 0)
                //{
                //    if (null == addrDal)
                //    {
                //        addrDal = new addressregisterManager();
                //    }
                //    hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
                //}
                //SetRegister("comb_thr_L0", Convert.ToUInt32(comb_thr_L0.Text, 16), hdrList);
                comb_thr_L0_Leave(sender, null);
            }
        }

        private void comb_thr_L0_Leave(object sender, EventArgs e)
        {
            //if (hdrList.Count == 0)
            //{
            //    if (null == addrDal)
            //    {
            //        addrDal = new addressregisterManager();
            //    }
            //    hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
            //}
            //SetRegister("comb_thr_L0", Convert.ToUInt32(comb_thr_L0.Text, 16), hdrList);
            if (isWrite) return;
            //if (null != sPortTemp && sPortTemp.IsOpen)
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (Convert.ToInt32(txt.Text, 16) > 0x90)
                {
                    txt.Text = "90";
                }
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipHDR.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetHDRRegister(model, Val);
                }
            }
        }



        private void comb_thr_S0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                //if (hdrList.Count == 0)
                //{
                //    if (null == addrDal)
                //    {
                //        addrDal = new addressregisterManager();
                //    }
                //    hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
                //}
                //SetRegister("comb_thr_S0", Convert.ToUInt32(comb_thr_S0.Text, 16), hdrList);
                comb_thr_S0_Leave(sender, null);
            }
        }

        private void comb_thr_S0_Leave(object sender, EventArgs e)
        {
            //if (hdrList.Count == 0)
            //{
            //    if (null == addrDal)
            //    {
            //        addrDal = new addressregisterManager();
            //    }
            //    hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
            //}
            //SetRegister("comb_thr_S0", Convert.ToUInt32(comb_thr_S0.Text, 16), hdrList);
            if (isWrite) return;
            //if (null != sPortTemp && sPortTemp.IsOpen)
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (Convert.ToInt32(txt.Text, 16) > 0x90)
                {
                    txt.Text = "90";
                }
                if (XChipHDR.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetHDRRegister(model, Val);
                }
            }
        }



        private void comb_thr_LS0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                //if (hdrList.Count == 0)
                //{
                //    if (null == addrDal)
                //    {
                //        addrDal = new addressregisterManager();
                //    }
                //    hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
                //}
                //SetRegister("comb_thr_LS0", Convert.ToUInt32(comb_thr_LS0.Text, 16), hdrList);
                comb_thr_LS0_Leave(sender, null);
            }
        }

        private void comb_thr_LS0_Leave(object sender, EventArgs e)
        {
            //if (hdrList.Count == 0)
            //{
            //    if (null == addrDal)
            //    {
            //        addrDal = new addressregisterManager();
            //    }
            //    hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
            //}
            //SetRegister("comb_thr_LS0", Convert.ToUInt32(comb_thr_LS0.Text, 16), hdrList);
            if (isWrite) return;
            //if (null != sPortTemp && sPortTemp.IsOpen)
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (Convert.ToInt32(txt.Text, 16) > 0x90)
                {
                    txt.Text = "90";
                }
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipHDR.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetHDRRegister(model, Val);
                }
            }
        }



        private void comb_thr_V0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                //if (hdrList.Count == 0)
                //{
                //    if (null == addrDal)
                //    {
                //        addrDal = new addressregisterManager();
                //    }
                //    hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
                //}
                //SetRegister("comb_thr_V0", Convert.ToUInt32(comb_thr_V0.Text, 16), hdrList);
                comb_thr_V0_Leave(sender, null);
            }
        }

        private void comb_thr_V0_Leave(object sender, EventArgs e)
        {
            //if (hdrList.Count == 0)
            //{
            //    if (null == addrDal)
            //    {
            //        addrDal = new addressregisterManager();
            //    }
            //    hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
            //}
            //SetRegister("comb_thr_V0", Convert.ToUInt32(comb_thr_V0.Text, 16), hdrList);
            if (isWrite) return;
            //if (null != sPortTemp && sPortTemp.IsOpen)
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (Convert.ToInt32(txt.Text, 16) > 0x90)
                {
                    txt.Text = "90";
                }
                if (XChipHDR.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetHDRRegister(model, Val);
                }
            }
        }



        private void ratio_list0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                //if (hdrList.Count == 0)
                //{
                //    if (null == addrDal)
                //    {
                //        addrDal = new addressregisterManager();
                //    }
                //    hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
                //}
                //SetRegister("ratio_list0", Convert.ToUInt32(ratio_list0.Text, 16), hdrList);
                ratio_list0_Leave(sender, null);
            }
        }

        private void ratio_list0_Leave(object sender, EventArgs e)
        {
            //if (hdrList.Count == 0)
            //{
            //    if (null == addrDal)
            //    {
            //        addrDal = new addressregisterManager();
            //    }
            //    hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
            //}
            //SetRegister("ratio_list0", Convert.ToUInt32(ratio_list0.Text, 16), hdrList);
            if (isWrite) return;
            //if (null != sPortTemp && sPortTemp.IsOpen)
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipHDR.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetHDRRegister(model, Val);
                }
            }
        }



        private void compression_list0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                //if (hdrList.Count == 0)
                //{
                //    if (null == addrDal)
                //    {
                //        addrDal = new addressregisterManager();
                //    }
                //    hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
                //}
                //SetRegister("compression_list0", Convert.ToUInt32(compression_list0.Text, 16), hdrList);
                compression_list0_Leave(sender, null);
            }
        }

        private void compression_list0_Leave(object sender, EventArgs e)
        {
            //if (hdrList.Count == 0)
            //{
            //    if (null == addrDal)
            //    {
            //        addrDal = new addressregisterManager();
            //    }
            //    hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
            //}
            //SetRegister("compression_list0", Convert.ToUInt32(compression_list0.Text, 16), hdrList);
            if (isWrite) return;
            //if (null != sPortTemp && sPortTemp.IsOpen)
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipHDR.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_h"))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == (txt.Name + "_h").ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetHDRRegister(model, Val);
                }
                if (XChipHDR.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_l"))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == (txt.Name + "_l").ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetHDRRegister(model, Val);
                }
            }
        }



        private void offset_manual_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                //if (hdrList.Count == 0)
                //{
                //    if (null == addrDal)
                //    {
                //        addrDal = new addressregisterManager();
                //    }
                //    hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
                //}
                //SetRegister("offset_manual", Convert.ToUInt32(offset_manual.Text, 16), hdrList);
                offset_manual_Leave(sender, null);
            }
        }

        private void offset_manual_Leave(object sender, EventArgs e)
        {
            //if (hdrList.Count == 0)
            //{
            //    if (null == addrDal)
            //    {
            //        addrDal = new addressregisterManager();
            //    }
            //    hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
            //}
            //SetRegister("offset_manual", Convert.ToUInt32(offset_manual.Text, 16), hdrList);
            if (isWrite) return;
            //if (null != sPortTemp && sPortTemp.IsOpen)
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipHDR.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_h"))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == (txt.Name + "_h").ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetHDRRegister(model, Val);
                }
                if (XChipHDR.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_l"))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == (txt.Name + "_l").ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetHDRRegister(model, Val);
                }
            }
        }

        private void gain_manual_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                gain_manual_Leave(sender, null);
            }
        }

        private void gain_manual_Leave(object sender, EventArgs e)
        {
            //if (hdrList.Count == 0)
            //{
            //    if (null == addrDal)
            //    {
            //        addrDal = new addressregisterManager();
            //    }
            //    hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
            //}
            //SetRegister("gain_manual", Convert.ToUInt32(gain_manual.Text, 16), hdrList);

            if (isWrite) return;
            //if (null != sPortTemp && sPortTemp.IsOpen)
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipHDR.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_h"))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == (txt.Name + "_h").ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetHDRRegister(model, Val);
                }
                if (XChipHDR.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_m0"))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == (txt.Name + "_m0").ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetHDRRegister(model, Val);
                }
                if (XChipHDR.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_l"))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == (txt.Name + "_l").ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetHDRRegister(model, Val);
                }
            }
        }

        private void hist_thr_highlight_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                //if (hdrList.Count == 0)
                //{
                //    if (null == addrDal)
                //    {
                //        addrDal = new addressregisterManager();
                //    }
                //    hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
                //}
                //SetRegister("hist_thr_highlight", Convert.ToUInt32(hist_thr_highlight.Text, 16), hdrList);
                hist_thr_highlight_Leave(sender, null);
            }
        }

        private void hist_thr_highlight_Leave(object sender, EventArgs e)
        {
            //if (hdrList.Count == 0)
            //{
            //    if (null == addrDal)
            //    {
            //        addrDal = new addressregisterManager();
            //    }
            //    hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
            //}
            //SetRegister("hist_thr_highlight", Convert.ToUInt32(hist_thr_highlight.Text, 16), hdrList);

            if (isWrite) return;
            //if (null != sPortTemp && sPortTemp.IsOpen)
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipHDR.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_h"))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == (txt.Name + "_h").ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetHDRRegister(model, Val);
                }
                if (XChipHDR.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_l"))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == (txt.Name + "_l").ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetHDRRegister(model, Val);
                }
            }
        }

        private void hist_thr_lowlight_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                //if (hdrList.Count == 0)
                //{
                //    if (null == addrDal)
                //    {
                //        addrDal = new addressregisterManager();
                //    }
                //    hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
                //}
                //SetRegister("hist_thr_lowlight", Convert.ToUInt32(hist_thr_lowlight.Text, 16), hdrList);
                hist_thr_lowlight_Leave(sender, null);
            }
        }

        private void hist_thr_lowlight_Leave(object sender, EventArgs e)
        {
            //if (hdrList.Count == 0)
            //{
            //    if (null == addrDal)
            //    {
            //        addrDal = new addressregisterManager();
            //    }
            //    hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
            //}
            //SetRegister("hist_thr_lowlight", Convert.ToUInt32(hist_thr_lowlight.Text, 16), hdrList);
            if (isWrite) return;
            //if (null != sPortTemp && sPortTemp.IsOpen)
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipHDR.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_h"))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == (txt.Name + "_h").ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetHDRRegister(model, Val);
                }
                if (XChipHDR.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_l"))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == (txt.Name + "_l").ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetHDRRegister(model, Val);
                }
            }
        }


        #endregion

        private void comb_weight_LS_00_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                comb_weight_LS_00_Leave(sender, null);

            }
        }

        private void comb_weight_LS_00_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            if (hdrList.Count == 0)
            {
                if (null == addrDal)
                {
                    addrDal = new addressregisterManager();
                }
                hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
            }
            var combtxt = sender as TextEdit;
            if (Convert.ToInt32(combtxt.Text, 16) > 0x80)
            {
                combtxt.Text = "80";
            }
            //var mstr = modeSelRadio.SelectedIndex == 0 ? "hl" : "ll";
            var mstr = "hl";
            SetRegister($"comb_weight_LS_{mstr}_{combtxt.Tag.ToString()}", Convert.ToUInt32(combtxt.Text, 16), hdrList);


        }

        private void comb_weight_LSV_00_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                comb_weight_LSV_00_Leave(sender, null);
            }
        }

        private void comb_weight_LSV_00_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            if (hdrList.Count == 0)
            {
                if (null == addrDal)
                {
                    addrDal = new addressregisterManager();
                }
                hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
            }
            var combtxt = sender as TextEdit;
            if (Convert.ToInt32(combtxt.Text, 16) > 0x80)
            {
                combtxt.Text = "80";
            }
            //var mstr = modeSelRadio.SelectedIndex == 0 ? "hl" : "ll";
            var mstr = "hl";
            SetRegister($"comb_weight_LSV_{mstr}_{combtxt.Tag.ToString()}", Convert.ToUInt32(combtxt.Text, 16), hdrList);
        }



        private void tabPane1_SelectedPageIndexChanged(object sender, EventArgs e)
        {
            if (tabPane1.SelectedPageIndex == 0)
            {
                xChip_HDR_Ae.sPortTemp = sPortTemp;
                xChip_HDR_Ae.IsUsbOpen = IsUsbOpen;
                xChip_HDR_Ae.m_open = m_open;
            }
            if (tabPane1.SelectedPageIndex == 1)
            {
                xChip_HDR_GAMMA1.sPortTemp = sPortTemp;
                xChip_HDR_GAMMA1.IsUsbOpen = IsUsbOpen;
                xChip_HDR_GAMMA1.m_open = m_open;
            }
            if (tabPane1.SelectedPageIndex == 2)
            {
                xChip_HDR_GAMMA1.sPortTemp = sPortTemp;
                xChip_HDR_GAMMA1.IsUsbOpen = IsUsbOpen;
                xChip_HDR_GAMMA1.m_open = m_open;
                //xChip_HDR_Ae1.aBll = aBll;
                //xChip_HDR_Ae1.XChipHDRAe = aBll.GetList(c => c.ChipType == ConfigurationManager.AppSettings["xc151_ChipType"] && (c.Classify == "HDR_AE" || c.Classify == "Common"));
            }
        }
        /// <summary>
        /// sensor status
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void simpleButton3_Click(object sender, EventArgs e)
        {

            List<string> listfiltration = new List<string> { "exp_ratio_LS_l", "exp_ratio_LS_h", "exp_line_L_l", "exp_line_L_m0", "exp_line_L_h", "gain_L_l", "gain_L_h", "exp_ratio_SV_h", "exp_ratio_SV_l", "exp_line_S_l", "exp_line_S_m0", "exp_line_S_h", "gain_S_l", "gain_S_h", "exp_line_V_l", "exp_line_V_h", "exp_line_V_m0", "gain_V_h", "gain_V_l", "combine_preferLong_str" };
            List<string> NameList = new List<string>();
            // 记录开始时间和寄存器计数
            var startTime = DateTime.Now;
            int totalRegisterCount = 0;
            for (int i = 0; i < XChipHDR.Count; i++)
            {
                var type = AppHelper.NameTypeToString(XChipHDR[i].NameType);
                //加上单选框的_en
                if (XChipHDR[i].ControlType == "1")
                {
                    type = XChipHDR[i].NameType;
                }
                var col = this.Controls.Find(type, true);
                foreach (var item in col)
                {
                    if (NameList.Exists(c => c.Contains(type)))
                    {
                        continue;
                    }
                    else
                    {

                        //过滤掉指定寄存器
                        if (!listfiltration.Exists(c => c.Contains(item.Name.ToString())))
                        {
                            continue;
                        }
                        
                        if (item is TextEdit)
                        {
                            var nList = XChipHDR.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                            if (nList.Count == 0)
                            {
                                nList = XChipHDR.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                            }
                            if (nList.Count == 1)
                            {
                                // 单个寄存器读取
                                var address = nList[0].Address;
                                totalRegisterCount++;
                                await ReadRegisterAndUpdateTextAsync(address, item as TextEdit, nList[0].Bits, nList[0].Hex);
                            }
                            else
                            {
                                // 多个寄存器组合读取
                                totalRegisterCount += nList.Count;
                                await ReadMultipleRegistersAndUpdateTextAsync(nList, item as TextEdit);
                            }
                        }
                        else if (item is CheckEdit)
                        {
                            var nList = XChipHDR.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "1").ToList();
                            if (nList.Count == 1)
                            {
                                var address = nList[0].Address;
                                totalRegisterCount++;
                                await ReadRegisterAndUpdateCheckAsync(address, item as CheckEdit, nList[0].Bits, nList[0].Hex);
                            }
                        }
                     

                    }
                }
                NameList.Add(type);
            }
            //string Vals = string.Empty;
            //Vals += SerialSend.ReadRegister(Convert.ToUInt32(XChipHDR.Find(c=>c.NameType.Contains("gain_L_l")).Address,16), sPortTemp).ToString("X2");
            //Vals += SerialSend.ReadRegister(Convert.ToUInt32(XChipHDR.Find(c => c.NameType.Contains("gain_L_h")).Address, 16), sPortTemp).ToString("X2");
            //gain_L.Text = Vals;
        }



        private async void simpleButton4_Click(object sender, EventArgs e)
        {
            CheckMethod();
            var H =(await ReadRegisterAsync(XChipHDR.Find(c => c.NameType.ToLower() == ($"hdr_oer_l_h").ToLower()).Address)).ToString("X2");
            var L = (await ReadRegisterAsync(XChipHDR.Find(c => c.NameType.ToLower() == ($"hdr_oer_l_l").ToLower()).Address)).ToString("X2");

            hdr_oer_l.Text = H + L;

            H = (await ReadRegisterAsync(XChipHDR.Find(c => c.NameType.ToLower() == ($"avgtext").ToLower()).Address)).ToString("X2");
            avgtext.Text = H;
            H = (await ReadRegisterAsync(XChipHDR.Find(c => c.NameType.ToLower() == ($"exp_ratio_LS_h").ToLower()).Address)).ToString("X2");
            L = (await ReadRegisterAsync(XChipHDR.Find(c => c.NameType.ToLower() == ($"exp_ratio_LS_l").ToLower()).Address)).ToString("X2");

            exp_ratio_LS.Text = H + L;
            H = (await ReadRegisterAsync(XChipHDR.Find(c => c.NameType.ToLower() == ($"exp_ratio_SV_h").ToLower()).Address)).ToString("X2");
            L = (await ReadRegisterAsync(XChipHDR.Find(c => c.NameType.ToLower() == ($"exp_ratio_SV_l").ToLower()).Address)).ToString("X2");

            exp_ratio_SV.Text = H + L;

            H = (await ReadRegisterAsync(XChipHDR.Find(c => c.NameType.ToLower() == ($"hist_thr_highlight_h").ToLower()).Address)).ToString("X2");
            L = (await ReadRegisterAsync(XChipHDR.Find(c => c.NameType.ToLower() == ($"hist_thr_highlight_l").ToLower()).Address)).ToString("X2");

            hist_thr_highlight.Text = H + L;
        }
        private async Task<long> GetHDRRegister(string nameType)
        {
            if (XChipHDR.Exists(c => c.NameType.ToLower() == nameType.ToLower()))
            {
                long var = await ReadRegisterAsync(XChipHDR.Where(c => c.NameType.ToLower() == nameType.ToLower()).First().Address);
                return var;
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($"未找到{nameType}"); return -1;
            }
        }

        private async Task SetHDRRegister(addressregister model, ulong add, bool isCheck = true)
        {
           
            if (isRead) return;

            bool success = await WriteRegisterAsync(model.Address, add.ToString("X"));

            if (!success)
            {
                Console.WriteLine($"[ADBForm] SetCfaRegister 写入失败 - 地址: {model.Address}, 值: {add:X}");
            }

        }

        private void panelControl13_Paint(object sender, PaintEventArgs e)
        {
            float move = 20f;
            float newX = panelControl6.Width - move;
            float newY = panelControl6.Height - move;
            //Y轴
            PointF px1 = new PointF(move, move);
            PointF px2 = new PointF(move, newY);
            PointF px3 = new PointF(move - 10, newY);
            Pen penAxis = new Pen(Brushes.Black, 1);
            e.Graphics.DrawString("V_Y", new Font("宋体", 10f), Brushes.Black, px3);
            penAxis.EndCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor;
            penAxis.CustomEndCap = new AdjustableArrowCap(4, 4, true);
            e.Graphics.DrawLine(penAxis, px1, px2);
            px1 = new PointF(move, move);
            px2 = new PointF(newX, move);
            px3 = new PointF(newX - 5, move - 15);
            e.Graphics.DrawLine(penAxis, px1, px2);
            e.Graphics.DrawString("F_Y", new Font("宋体", 10f), Brushes.Black, px3);
        }

        private void panelControl12_Paint(object sender, PaintEventArgs e)
        {
            float move = 20f;
            float newX = panelControl5.Width - move;
            float newY = panelControl5.Height - move;
            //Y轴
            PointF px1 = new PointF(move, move);
            PointF px2 = new PointF(move, newY);
            PointF px3 = new PointF(move - 10, newY);
            Pen penAxis = new Pen(Brushes.Black, 1);
            e.Graphics.DrawString("S_Y", new Font("宋体", 10f), Brushes.Black, px3);
            penAxis.EndCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor;
            penAxis.CustomEndCap = new AdjustableArrowCap(4, 4, true);
            e.Graphics.DrawLine(penAxis, px1, px2);
            px1 = new PointF(move, move);
            px2 = new PointF(newX - 10, move);
            px3 = new PointF(newX - 15, move - 15);
            e.Graphics.DrawLine(penAxis, px1, px2);
            e.Graphics.DrawString("L_Y", new Font("宋体", 10f), Brushes.Black, px3);
        }

        private async void simpleButton8_Click(object sender, EventArgs e)
        {
            if (null == addrDal)
            {
                addrDal = new addressregisterManager();
            }
            isRead = true;
            if (hdrList.Count == 0)
            {
                hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
            }
            WaitBefore.Start("读取中", "正在加载中", 10);
            // 记录开始时间和寄存器计数
            var startTime = DateTime.Now;
            int totalRegisterCount = 0;
            //var modeSel = GetRegister("scene_mode", hdrList);
            //modeSelRadio.SelectedIndex = (int)(modeSel & 0x01);
            //scene_mode.Text = modeSel.ToString("X2");
            CheckMethod();
            #region 文本框

            string nameType = string.Empty;

            List<string> NameList = new List<string>();
            for (int i = 0; i < XChipHDR.Count; i++)
            {
                if (XChipHDR[i].NameType.Contains("compression_list0"))
                {

                }
                var type = AppHelper.NameTypeToString(XChipHDR[i].NameType);
                //加上单选框的_en
                if (XChipHDR[i].ControlType == "1")
                {
                    type = XChipHDR[i].NameType;
                }
                var col = this.Controls.Find(type, true);

                foreach (var item in col)
                {
                    if (NameList.Exists(c => c == (type)))
                    {
                        continue;
                    }
                    else
                    {

                        if (item is TextEdit)
                        {
                            var nList = XChipHDR.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                            if (nList.Count == 0)
                            {
                                nList = XChipHDR.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                            }
                            if (nList.Count == 1)
                            {
                                // 单个寄存器读取
                                var address = nList[0].Address;
                                totalRegisterCount++;
                                await ReadRegisterAndUpdateTextAsync(address, item as TextEdit, nList[0].Bits, nList[0].Hex);
                            }
                            else
                            {
                                // 多个寄存器组合读取
                                totalRegisterCount += nList.Count;
                                await ReadMultipleRegistersAndUpdateTextAsync(nList, item as TextEdit);
                            }
                        }
                        else if (item is CheckEdit)
                        {
                            var nList = XChipHDR.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "1").ToList();
                            if (nList.Count == 1)
                            {
                                var address = nList[0].Address;
                                totalRegisterCount++;
                                await ReadRegisterAndUpdateCheckAsync(address, item as CheckEdit, nList[0].Bits, nList[0].Hex);
                            }
                        }
                        NameList.Add(item.Name);

                    }
                }
                NameList.Add(type);
            }
            //string Vals = string.Empty;
            //Vals += SerialSend.ReadRegister(Convert.ToUInt32(XChipHDR.Find(c => c.NameType.Contains("gain_L_l")).Address, 16), sPortTemp).ToString("X2");
            //Vals += SerialSend.ReadRegister(Convert.ToUInt32(XChipHDR.Find(c => c.NameType.Contains("gain_L_h")).Address, 16), sPortTemp).ToString("X2");
            //gain_L.Text = Vals;
            //var mstr = modeSelRadio.SelectedIndex == 0 ? "hl" : "ll";
            var mstr = "hl";
            comb_weight_LS_00.Text =(await GetRegister($"comb_weight_LS_{mstr}_00")).ToString("X2");
            comb_weight_LS_01.Text = (await GetRegister($"comb_weight_LS_{mstr}_01")).ToString("X2");
            comb_weight_LS_02.Text = (await GetRegister($"comb_weight_LS_{mstr}_02")).ToString("X2");
            comb_weight_LS_03.Text = (await GetRegister($"comb_weight_LS_{mstr}_03")).ToString("X2");

            comb_weight_LS_10.Text = (await GetRegister($"comb_weight_LS_{mstr}_10")).ToString("X2");
            comb_weight_LS_11.Text = (await GetRegister($"comb_weight_LS_{mstr}_11")).ToString("X2");
            comb_weight_LS_12.Text = (await GetRegister($"comb_weight_LS_{mstr}_12")).ToString("X2");
            comb_weight_LS_13.Text = (await GetRegister($"comb_weight_LS_{mstr}_13")).ToString("X2");

            comb_weight_LS_20.Text = (await GetRegister($"comb_weight_LS_{mstr}_20")).ToString("X2");
            comb_weight_LS_21.Text = (await GetRegister($"comb_weight_LS_{mstr}_21")).ToString("X2");
            comb_weight_LS_22.Text = (await GetRegister($"comb_weight_LS_{mstr}_22")).ToString("X2");
            comb_weight_LS_23.Text = (await GetRegister($"comb_weight_LS_{mstr}_23")).ToString("X2");

            comb_weight_LS_30.Text = (await GetRegister($"comb_weight_LS_{mstr}_30")).ToString("X2");
            comb_weight_LS_31.Text = (await GetRegister($"comb_weight_LS_{mstr}_31")).ToString("X2");
            comb_weight_LS_32.Text = (await GetRegister($"comb_weight_LS_{mstr}_32")).ToString("X2");
            comb_weight_LS_33.Text = (await GetRegister($"comb_weight_LS_{mstr}_33")).ToString("X2");

            comb_weight_LSV_00.Text = (await GetRegister($"comb_weight_LSV_{mstr}_00")).ToString("X2");
            comb_weight_LSV_01.Text = (await GetRegister($"comb_weight_LSV_{mstr}_01")).ToString("X2");
            comb_weight_LSV_02.Text = (await GetRegister($"comb_weight_LSV_{mstr}_02")).ToString("X2");
            comb_weight_LSV_03.Text = (await GetRegister($"comb_weight_LSV_{mstr}_03")).ToString("X2");

            comb_weight_LSV_10.Text = (await GetRegister($"comb_weight_LSV_{mstr}_10")).ToString("X2");
            comb_weight_LSV_11.Text = (await GetRegister($"comb_weight_LSV_{mstr}_11")).ToString("X2");
            comb_weight_LSV_12.Text = (await GetRegister($"comb_weight_LSV_{mstr}_12")).ToString("X2");
            comb_weight_LSV_13.Text = (await GetRegister($"comb_weight_LSV_{mstr}_13")).ToString("X2");

            comb_weight_LSV_20.Text = (await GetRegister($"comb_weight_LSV_{mstr}_20")).ToString("X2");
            comb_weight_LSV_21.Text = (await GetRegister($"comb_weight_LSV_{mstr}_21")).ToString("X2");
            comb_weight_LSV_22.Text = (await GetRegister($"comb_weight_LSV_{mstr}_22")).ToString("X2");
            comb_weight_LSV_23.Text = (await GetRegister($"comb_weight_LSV_{mstr}_23")).ToString("X2");

            comb_weight_LSV_30.Text = (await GetRegister($"comb_weight_LSV_{mstr}_30")).ToString("X2");
            comb_weight_LSV_31.Text = (await GetRegister($"comb_weight_LSV_{mstr}_31")).ToString("X2");
            comb_weight_LSV_32.Text = (await GetRegister($"comb_weight_LSV_{mstr}_32")).ToString("X2");
            comb_weight_LSV_33.Text = (await GetRegister($"comb_weight_LSV_{mstr}_33")).ToString("X2");
            //hdrgammma
            ratio_highlight.Text =(await GetRegister("ratio_highlight", hdrList)).ToString("X2");
            string Vals = string.Empty;
            Vals +=( await ReadRegisterAsync(hdrList.Find(c => c.NameType.Contains("portion_highlight_h")).Address)).ToString("X2");
            Vals +=( await ReadRegisterAsync(hdrList.Find(c => c.NameType.Contains("portion_highlight_l")).Address)).ToString("X2");
            portion_lighlight.Text = Vals;
            #endregion
            var combine = await ReadRegisterAsync(hdrList.Where(c => c.NameType.ToLower() == "combine_mode_en".ToLower()).First().Address);
            if (combine == 0x80)
            {
                Mode_switch.Properties.Items[3].Enabled = false;
            }
            else if (combine == 0xC0)
            {
                Mode_switch.Properties.Items[3].Enabled = true;
            }
            var HDRmodeVal = (await ReadRegisterAsync(hdrList.Where(c => c.NameType.ToLower() == "HDRmode0".ToLower()).First().Address)).ToString("X");
            bool HDRmode0 = BitsHelp.GetBitsCheckedToBool(hdrList.Where(c => c.NameType.ToLower() == "HDRmode0".ToLower()).First().Bits, hdrList.Where(c => c.NameType.ToLower() == "HDRmode0".ToLower()).First().Hex, HDRmodeVal) == 0;
            HDRmodeVal = (await ReadRegisterAsync(hdrList.Where(c => c.NameType.ToLower() == "HDRmode1".ToLower()).First().Address)).ToString("X");
            bool HDRmode1 = BitsHelp.GetBitsCheckedToBool(hdrList.Where(c => c.NameType.ToLower() == "HDRmode1".ToLower()).First().Bits, hdrList.Where(c => c.NameType.ToLower() == "HDRmode1".ToLower()).First().Hex, HDRmodeVal) == 0;
            HDRmodeVal = (await ReadRegisterAsync(hdrList.Where(c => c.NameType.ToLower() == "HDRmode2".ToLower()).First().Address)).ToString("X");
            bool HDRmode2 = BitsHelp.GetBitsCheckedToBool(hdrList.Where(c => c.NameType.ToLower() == "HDRmode2".ToLower()).First().Bits, hdrList.Where(c => c.NameType.ToLower() == "HDRmode2".ToLower()).First().Hex, HDRmodeVal) == 0;
            if (HDRmode0 && !HDRmode1 && !HDRmode1)
            {
                Mode_switch.SelectedIndex = 0;
            }
            else if (!HDRmode0 && !HDRmode1 && !HDRmode2)
            {
                Mode_switch.SelectedIndex = 1;
            }
            else if (!HDRmode0 && HDRmode1 && !HDRmode2)
            {
                Mode_switch.SelectedIndex = 2;
            }
            else if (!HDRmode0 && !HDRmode1 && HDRmode2)
            {
                Mode_switch.SelectedIndex = 3;
            }
            EnShowHide();
            Statusvalue();

            isRead = false;
            WaitBefore.Close();
        }


        #region ADB异步读写


        /// <summary>
        /// 异步读取单个寄存器并更新文本框
        /// </summary>
        private async Task ReadRegisterAndUpdateTextAsync(string address, TextEdit textEdit, string bits, string hex)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取寄存器: {address}");

                // 发送读取命令
                string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{address},0,0\"";
                await adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{address}");

                // 等待命令执行
                await Task.Delay(10);

                // 获取寄存器值
                var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Read", 500));

                if (record != null && !string.IsNullOrEmpty(record.Values) && record.Values != "0")
                {
                    string processedValue = record.Values;
                    if (processedValue.StartsWith("0x"))
                    {
                        processedValue = processedValue.Substring(2);
                    }

                    Console.WriteLine($"[ADBForm] 成功读取寄存器 {address} 值: {processedValue}");

                    // 处理位操作
                    string displayValue;
                    if (processedValue != "0")
                    {
                        var uintValue = BitsHelp.GetBitsToUint(bits, hex, processedValue);
                        displayValue = uintValue.ToString("X");
                        Console.WriteLine($"[ADBForm] 寄存器 {address} Bits处理后值: {displayValue} (bits:{bits}, hex:{hex})");
                    }
                    else
                    {
                        displayValue = "0";
                    }

                    // 更新UI
                    UpdateTextEdit(textEdit, displayValue);
                }
                else
                {
                    Console.WriteLine($"[ADBForm] 读取寄存器 {address} 失败，值为空或0，使用默认值0");
                    UpdateTextEdit(textEdit, "0");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取寄存器 {address} 异常: {ex.Message}");
                UpdateTextEdit(textEdit, "错误");
            }
        }

        /// <summary>
        /// 异步读取多个寄存器并组合更新文本框
        /// </summary>
        private async Task ReadMultipleRegistersAndUpdateTextAsync(List<addressregister> nList, TextEdit textEdit)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取多个寄存器，数量: {nList.Count}");

                string combinedValue = string.Empty;

                // 按预定义的优先级顺序读取寄存器
                var priorityOrder = new[] { "_h", "_m0", "_m1", "_m2", "_m3", "_l" };

                foreach (var priority in priorityOrder)
                {
                    addressregister register = FindRegisterByPriority(nList, priority);

                    if (register != null)
                    {
                        Console.WriteLine($"[ADBForm] 读取优先级 '{priority}' 的寄存器: {register.NameType} ({register.Address})");

                        // 发送读取命令
                        string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{register.Address},0,0\"";
                        await adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{register.Address}");

                        // 等待命令执行
                        await Task.Delay(10);

                        // 获取寄存器值
                        var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(register.Address, "Read", 500));

                        if (record != null && !string.IsNullOrEmpty(record.Values) && record.Values != "0")
                        {
                            string processedValue = record.Values;
                            if (processedValue.StartsWith("0x"))
                            {
                                processedValue = processedValue.Substring(2);
                            }

                            combinedValue += processedValue.PadLeft(2, '0');
                            Console.WriteLine($"[ADBForm] 成功读取 {register.Address}，当前组合值: {combinedValue}");
                        }
                        else
                        {
                            combinedValue += "00";
                            Console.WriteLine($"[ADBForm] 读取 {register.Address} 失败，使用默认值00，当前组合值: {combinedValue}");
                        }
                    }
                    else
                    {
                        Console.WriteLine($"[ADBForm] 未找到包含 '{priority}' 的寄存器");
                    }
                }

                Console.WriteLine($"[ADBForm] 最终组合值: {combinedValue}");

                // 更新UI
                UpdateTextEdit(textEdit, combinedValue);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取多个寄存器失败: {ex.Message}");
                UpdateTextEdit(textEdit, "错误");
            }
        }

        /// <summary>
        /// 根据优先级查找寄存器
        /// </summary>
        private addressregister FindRegisterByPriority(List<addressregister> nList, string priority)
        {
            if (priority == "_l")
            {
                // 特殊处理 _l 寄存器
                if (nList.Exists(c => c.NameType.ToLower().Contains("_l")))
                {
                    // 首先查找以 "_l" 结尾的寄存器
                    var exactMatch = nList.Find(c => c.NameType.ToLower().EndsWith("_l"));
                    if (exactMatch != null)
                    {
                        Console.WriteLine($"[ADBForm] 找到以 '_l' 结尾的寄存器: {exactMatch.NameType}");
                        return exactMatch;
                    }
                    else
                    {
                        // 如果没有以 "_l" 结尾的，则使用最后一个包含 "_l" 的寄存器
                        var containsMatch = nList.Last(c => c.NameType.ToLower().Contains("_l"));
                        Console.WriteLine($"[ADBForm] 找到包含 '_l' 的寄存器: {containsMatch.NameType}");
                        return containsMatch;
                    }
                }
            }
            else
            {
                // 其他寄存器正常处理
                var register = nList.Find(c => c.NameType.ToLower().Contains(priority));
                if (register != null)
                {
                    Console.WriteLine($"[ADBForm] 找到包含 '{priority}' 的寄存器: {register.NameType}");
                    return register;
                }
            }

            return null;
        }

        /// <summary>
        /// 更新文本框的辅助方法
        /// </summary>
        private void UpdateTextEdit(TextEdit textEdit, string value)
        {
            if (textEdit.InvokeRequired)
            {
                textEdit.Invoke(new Action(() =>
                {
                    textEdit.Text = value;
                    Console.WriteLine($"[ADBForm] UI已更新，文本框值: {value}");
                }));
            }
            else
            {
                textEdit.Text = value;
                Console.WriteLine($"[ADBForm] UI已更新，文本框值: {value}");
            }
        }

        /// <summary>
        /// 异步读取寄存器并更新复选框
        /// </summary>
        private async Task ReadRegisterAndUpdateCheckAsync(string address, CheckEdit checkEdit, string bits, string hex)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取寄存器并更新复选框: {address}");

                string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{address},0,0\"";
                await adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{address}");

                // 等待命令执行
                await Task.Delay(10);

                var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Read", 500));

                bool isChecked = false;
                if (!string.IsNullOrEmpty(record.Values) && record.Values != "0")
                {
                    isChecked = BitsHelp.GetBitsCheckedToBool(bits, hex, record.Values) == 0;
                    Console.WriteLine($"[ADBForm] 复选框更新 - 地址:{address}, 值:{record.Values}, 状态:{isChecked}");
                }
                else
                {
                    Console.WriteLine($"[ADBForm] 复选框更新 - 地址:{address}, 值无效, 状态:false");
                }

                // 更新UI
                if (checkEdit.InvokeRequired)
                {
                    checkEdit.Invoke(new Action(() => checkEdit.Checked = isChecked));
                }
                else
                {
                    checkEdit.Checked = isChecked;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取寄存器 {address} 更新复选框失败: {ex.Message}");
                if (checkEdit.InvokeRequired)
                {
                    checkEdit.Invoke(new Action(() => checkEdit.Checked = false));
                }
                else
                {
                    checkEdit.Checked = false;
                }
            }
        }

        /// <summary>
        /// 异步读取单个寄存器返回值
        /// </summary>
        private async Task<long> ReadRegisterAsync(string address)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取寄存器: {address}");
                // 发送读取命令
                string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{address},0,0\"";
                await adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{address}");

                // 等待命令执行
                await Task.Delay(10);

                // 获取寄存器值
                var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Read", 500));

                if (record != null && !string.IsNullOrEmpty(record.Values) && record.Values != "0")
                {
                    return Convert.ToInt32(record.Values, 16);
                }
                else
                {
                    Console.WriteLine($"[ADBForm] 读取寄存器 {address} 失败，值为空或0，使用默认值0");
                    return 0;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取寄存器 {address} 异常: {ex.Message}");
                return 0;
            }
        }
        /// <summary>
        /// 异步写入单个寄存器，在值不匹配时自动重试一次
        /// </summary>
        private async Task<bool> WriteRegisterAsync(string address, string value)
        {
            int maxRetries = 1; // 值不匹配时最多重试一次
            int retryCount = 0;

            while (retryCount <= maxRetries)
            {
                try
                {
                    if (retryCount > 0)
                    {
                        Console.WriteLine($"[ADBForm] 第 {retryCount} 次重试写入寄存器: {address} 值: {value}");
                    }
                    else
                    {
                        Console.WriteLine($"[ADBForm] 开始写入寄存器: {address} 值: {value}");
                    }

                    // 处理位操作（如果有）
                    string processedValue = value;

                    // 确保值是十六进制格式（不带0x前缀）
                    if (processedValue.StartsWith("0x"))
                    {
                        processedValue = processedValue.Substring(2);
                    }

                    // 发送写入命令
                    string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"1,{address},{processedValue},0\"";
                    adbService.ExecuteAdbCommandAsync(adbCommand, $"写操作 - 地址:{address} 值:{processedValue}");

                    // 等待命令执行
                    await Task.Delay(10);

                    // 验证写入是否成功 - 等待写入记录出现
                    var writeRecord = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Write", 500));

                    if (writeRecord != null && !string.IsNullOrEmpty(writeRecord.Values))
                    {
                        string actualValue = writeRecord.Values;
                        if (actualValue.StartsWith("0x"))
                        {
                            actualValue = actualValue.Substring(2);
                        }

                        // 比较写入的值是否匹配
                        bool success = string.Equals(actualValue, processedValue, StringComparison.OrdinalIgnoreCase);

                        if (success)
                        {
                            Console.WriteLine($"[ADBForm] 成功写入寄存器 {address} 值: {processedValue}");
                            return true;
                        }
                        else
                        {
                            Console.WriteLine($"[ADBForm] 写入寄存器 {address} 值不匹配，期望: {processedValue}，实际: {actualValue}");

                            // 如果不匹配且还有重试次数，则继续重试
                            if (retryCount < maxRetries)
                            {
                                retryCount++;
                                Console.WriteLine($"[ADBForm] 准备重试写入...");
                                continue; // 直接进入下一次循环，重新发送命令
                            }
                            else
                            {
                                Console.WriteLine($"[ADBForm] 写入寄存器 {address} 重试次数已用完，仍然不匹配");
                                return false;
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine($"[ADBForm] 写入寄存器 {address} 失败，未找到写入确认记录");

                        // 如果未找到记录且还有重试次数，则重试
                        if (retryCount < maxRetries)
                        {
                            retryCount++;
                            Console.WriteLine($"[ADBForm] 准备重试写入...");
                            continue;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[ADBForm] 写入寄存器 {address} 异常: {ex.Message}");

                    // 如果异常且还有重试次数，则重试
                    if (retryCount < maxRetries)
                    {
                        retryCount++;
                        Console.WriteLine($"[ADBForm] 准备重试写入...");
                        await Task.Delay(10); // 异常后稍作延迟再重试
                        continue;
                    }
                    else
                    {
                        return false;
                    }
                }
            }

            return false; // 理论上不会执行到这里
        }




        #endregion

        private void Statusvalue()
        {
            if (tome_mapping_en.Checked)
            {
                hist_thr_highlight.Enabled = false;
            }
            else
            {
                hist_thr_highlight.Enabled = true;
            }
            if (combine_preferLong_en.Checked)
            {
                weight_hds_en.Enabled = true;
                weight_gain_en.Enabled = true;
                weight_man_en.Enabled = true;
            }
            else
            {
                weight_hds_en.Enabled = false;
                weight_gain_en.Enabled = false;
                weight_man_en.Enabled = false;
            }
            if (weight_hds_en.Checked || weight_gain_en.Checked || weight_man_en.Checked)
            {
                combine_preferLong_str.Enabled = false;
            }
            else
            {
                combine_preferLong_str.Enabled = true;
            }
        }
        private async void combwt_man_en_CheckedChanged(object sender, EventArgs e)
        {
            var chk = sender as CheckEdit;
            if (isRead) return;
            if (XChipHDR.Exists(c => c.NameType.ToLower() == (chk.Name).ToLower()))
            {
                var model = XChipHDR.Find(c => c.NameType.ToLower() == (chk.Name).ToLower());
                var Add = await ReadRegisterAsync(model.Address);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), chk.Checked);
               await SetHDRRegister(model, Val);
            }
            EnShowHide();
        }

        private async void combine_preferLong_en_CheckedChanged(object sender, EventArgs e)
        {
            var chk = sender as CheckEdit;
            if (isRead) return;
            if (XChipHDR.Exists(c => c.NameType.ToLower() == (chk.Name).ToLower()))
            {
                var model = XChipHDR.Find(c => c.NameType.ToLower() == (chk.Name).ToLower());
                var Add = await ReadRegisterAsync(model.Address);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), chk.Checked);
                await SetHDRRegister(model, Val);
            }
            EnShowHide();
            Statusvalue();
        }

        private void combwt_man_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            var txtedit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtedit.Text)) return;
            //SetSDERegister("SDE_SATV", (ulong)Convert.ToInt32(txtedit.Text, 16));
            if (XChipHDR.Exists(c => c.NameType.ToLower() == txtedit.Name.ToLower()))
            {
                var model = XChipHDR.Find(c => c.NameType.ToLower() == txtedit.Name.ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
                SetHDRRegister(model, Val);
            }
        }

        private async void combine_preferLong_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            var txtedit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtedit.Text)) return;
            if (XChipHDR.Exists(c => c.NameType.ToLower() == txtedit.Name.ToLower()))
            {
                var model = XChipHDR.Find(c => c.NameType.ToLower() == txtedit.Name.ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtedit.Text);
               await SetHDRRegister(model, Val);
            }
        }

        private void combwt_man_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                combwt_man_Leave(sender, null);
            }
        }

        private void combine_preferLong_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                combine_preferLong_Leave(sender, null);
            }
        }

        private async void Mode_switch_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (Mode_switch.EditValue.ToString() == "1")
            {
                if (XChipHDR.Exists(c => c.NameType.ToLower() == "HDRmode0".ToLower()))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == "HDRmode0".ToLower());
                    //var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex,"1");
                    var Add = await ReadRegisterAsync(model.Address);
                    var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), true);
                    await SetHDRRegister(model, Val);
                }
                if (XChipHDR.Exists(c => c.NameType.ToLower() == "HDRmode1".ToLower()))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == "HDRmode1".ToLower());
                    //var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, "0");
                    var Add = await ReadRegisterAsync(model.Address);
                    var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), false);
                    await SetHDRRegister(model, Val);
                }
                if (XChipHDR.Exists(c => c.NameType.ToLower() == "HDRmode2".ToLower()))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == "HDRmode2".ToLower());
                    //var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, "0");
                    var Add = await ReadRegisterAsync(model.Address);
                    var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), false);
                    await SetHDRRegister(model, Val);
                }
            }
            else if (Mode_switch.EditValue.ToString() == "2")
            {
                if (XChipHDR.Exists(c => c.NameType.ToLower() == "HDRmode0".ToLower()))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == "HDRmode0".ToLower());
                    //var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, "0");
                    var Add = await ReadRegisterAsync(model.Address);
                    var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), false);
                    await SetHDRRegister(model, Val);
                }
                if (XChipHDR.Exists(c => c.NameType.ToLower() == "HDRmode1".ToLower()))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == "HDRmode1".ToLower());
                    //var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, "0");
                    var Add = await ReadRegisterAsync(model.Address);
                    var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), false);
                    await SetHDRRegister(model, Val);
                }
                if (XChipHDR.Exists(c => c.NameType.ToLower() == "HDRmode2".ToLower()))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == "HDRmode2".ToLower());
                    //var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, "0");
                    var Add = await ReadRegisterAsync(model.Address);
                    var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), false);
                    await SetHDRRegister(model, Val);
                }
            }
            else if (Mode_switch.EditValue.ToString() == "3")
            {
                if (XChipHDR.Exists(c => c.NameType.ToLower() == "HDRmode0".ToLower()))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == "HDRmode0".ToLower());
                    // var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, "0");
                    var Add = await ReadRegisterAsync(model.Address);
                    var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), false);
                    await SetHDRRegister(model, Val);
                }
                if (XChipHDR.Exists(c => c.NameType.ToLower() == "HDRmode1".ToLower()))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == "HDRmode1".ToLower());
                    // var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, "1");
                    var Add = await ReadRegisterAsync(model.Address);
                    var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), true);
                    await SetHDRRegister(model, Val);
                }
                if (XChipHDR.Exists(c => c.NameType.ToLower() == "HDRmode2".ToLower()))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == "HDRmode2".ToLower());
                    // var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, "0");
                    var Add = await ReadRegisterAsync(model.Address);
                    var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), false);
                    await SetHDRRegister(model, Val);
                }
            }
            else if (Mode_switch.EditValue.ToString() == "4")
            {
                if (XChipHDR.Exists(c => c.NameType.ToLower() == "HDRmode0".ToLower()))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == "HDRmode0".ToLower());
                    //var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, "0");
                    var Add = await ReadRegisterAsync(model.Address);
                    var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), false);
                    await SetHDRRegister(model, Val);
                }
                if (XChipHDR.Exists(c => c.NameType.ToLower() == "HDRmode1".ToLower()))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == "HDRmode1".ToLower());
                    //var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, "0");
                    var Add = await ReadRegisterAsync(model.Address);
                    var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), false);
                    await SetHDRRegister(model, Val);
                }
                if (XChipHDR.Exists(c => c.NameType.ToLower() == "HDRmode2".ToLower()))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == "HDRmode2".ToLower());
                    //var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, "1");
                    var Add = await ReadRegisterAsync(model.Address);
                    var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), true);
                    await SetHDRRegister(model, Val);
                }
            }
        }

        private async void avg_list0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            //if (null != sPortTemp && sPortTemp.IsOpen)
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipHDR.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    await SetHDRRegister(model, Val);
                }
            }
        }

        private void avg_wave_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            //if (null != sPortTemp && sPortTemp.IsOpen)
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipHDR.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetHDRRegister(model, Val);
                }
            }
        }

        private void gamma_ratiolist0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            //if (null != sPortTemp && sPortTemp.IsOpen)
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipHDR.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetHDRRegister(model, Val);
                }
            }
        }

        private void weight_gainlist0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            //if (null != sPortTemp && sPortTemp.IsOpen)
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipHDR.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetHDRRegister(model, Val);
                }
            }
        }

        private async void weight_man_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            //if (null != sPortTemp && sPortTemp.IsOpen)
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipHDR.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                   await SetHDRRegister(model, Val);
                }
            }
        }

        private async void threshold_l_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            //if (null != sPortTemp && sPortTemp.IsOpen)
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipHDR.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_h"))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == (txt.Name + "_h").ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                  await  SetHDRRegister(model, Val);
                }
                if (XChipHDR.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_l"))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == (txt.Name + "_l").ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    await SetHDRRegister(model, Val);
                }
            }
        }

        private async void tome_mappinglist0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            //if (null != sPortTemp && sPortTemp.IsOpen)
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipHDR.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_h"))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == (txt.Name + "_h").ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                  await  SetHDRRegister(model, Val);
                }
                if (XChipHDR.Exists(c => c.NameType.ToLower() == txt.Name.ToLower() + "_l"))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == (txt.Name + "_l").ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    await SetHDRRegister(model, Val);
                }
            }
        }

        private void avg_wave_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                avg_wave_Leave(sender, null);
            }
        }

        private void avg_list0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                avg_list0_Leave(sender, null);
            }
        }

        private void gamma_ratiolist0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                gamma_ratiolist0_Leave(sender, null);
            }
        }

        private void tome_mappinglist0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                tome_mappinglist0_Leave(sender, null);
            }
        }

        private void threshold_l_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                threshold_l_Leave(sender, null);
            }
        }

        private void threshold_h_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                threshold_l_Leave(sender, null);
            }
        }

        private async void threshold_num_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            //if (null != sPortTemp && sPortTemp.IsOpen)
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipHDR.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                {
                    var model = XChipHDR.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                  await  SetHDRRegister(model, Val);
                }
            }
        }

        private void threshold_num_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                threshold_num_Leave(sender, null);
            }
        }

        private void weight_gainlist0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                weight_gainlist0_Leave(sender, null);
            }
        }

        private void weight_man_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                weight_man_Leave(sender, null);
            }
        }

        private async void weight_gain_en_CheckedChanged(object sender, EventArgs e)
        {
            var chk = sender as CheckEdit;
            if (isRead) return;
            if (XChipHDR.Exists(c => c.NameType.ToLower() == (chk.Name).ToLower()))
            {
                var model = XChipHDR.Find(c => c.NameType.ToLower() == (chk.Name).ToLower());
                var Add = await ReadRegisterAsync(model.Address);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), chk.Checked);
              await  SetHDRRegister(model, Val);
            }

            EnShowHide();
            Statusvalue();
        }

        private async void tome_mapping_en_CheckedChanged(object sender, EventArgs e)
        {
            var chk = sender as CheckEdit;
            if (isRead) return;
            if (XChipHDR.Exists(c => c.NameType.ToLower() == (chk.Name).ToLower()))
            {
                var model = XChipHDR.Find(c => c.NameType.ToLower() == (chk.Name).ToLower());
                var Add = await ReadRegisterAsync(model.Address);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), chk.Checked);
               await SetHDRRegister(model, Val);
            }
            EnShowHide();
            Statusvalue();
        }

        private async void weight_hds_en_CheckedChanged(object sender, EventArgs e)
        {
            var chk = sender as CheckEdit;
            if (isRead) return;
            if (XChipHDR.Exists(c => c.NameType.ToLower() == (chk.Name).ToLower()))
            {
                var model = XChipHDR.Find(c => c.NameType.ToLower() == (chk.Name).ToLower());
                var Add = await ReadRegisterAsync(model.Address);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), chk.Checked);
               await SetHDRRegister(model, Val);
            }
            EnShowHide();
            Statusvalue();
        }

        private async void gamma_ratio_en_CheckedChanged(object sender, EventArgs e)
        {
            var chk = sender as CheckEdit;
            if (isRead) return;
            if (XChipHDR.Exists(c => c.NameType.ToLower() == (chk.Name).ToLower()))
            {
                var model = XChipHDR.Find(c => c.NameType.ToLower() == (chk.Name).ToLower());
                var Add = await ReadRegisterAsync(model.Address);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), chk.Checked);
               await SetHDRRegister(model, Val);
            }
            EnShowHide();
        }

        private async void weight_man_en_CheckedChanged(object sender, EventArgs e)
        {
            var chk = sender as CheckEdit;
            if (isRead) return;
            if (XChipHDR.Exists(c => c.NameType.ToLower() == (chk.Name).ToLower()))
            {
                var model = XChipHDR.Find(c => c.NameType.ToLower() == (chk.Name).ToLower());
                var Add = await ReadRegisterAsync(model.Address);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), chk.Checked);
              await  SetHDRRegister(model, Val);
            }
            EnShowHide();
            Statusvalue();
        }

        private void XChip_HDR_Load(object sender, EventArgs e)
        {
            Task.Run(() => {
                this.Invoke((EventHandler)delegate {
                    for (int i = 0; i < XChipHDR.Count; i++)
                    {

                        var type = AppHelper.NameTypeToString(XChipHDR[i].NameType);

                        var col = this.Controls.Find(type, true);


                        foreach (var item in col)
                        {
                            if (item is TextEdit)
                            {
                                //声明一个SuerToolTip
                                DevExpress.Utils.SuperToolTip graduationBatchSuperToolTip = new DevExpress.Utils.SuperToolTip();
                                //声明一个ToolTipTitleItem,保存标题
                                DevExpress.Utils.ToolTipTitleItem toolTipTitleItem = new DevExpress.Utils.ToolTipTitleItem();
                                String tooltips = "";
                                if (!string.IsNullOrEmpty(XChipHDR[i].Bit_Wide))
                                {
                                    tooltips += $"位宽={XChipHDR[i].Bit_Wide}";
                                }
                                if (!string.IsNullOrEmpty(XChipHDR[i].Bit_Accuracy))
                                {
                                    tooltips += $"|精度={XChipHDR[i].Bit_Accuracy}";
                                }
                                //设置标题文字
                                toolTipTitleItem.Text = tooltips;
                                //把标题添加到SuerToolTip
                                graduationBatchSuperToolTip.Items.Add(toolTipTitleItem);
                                //指定控件的SuperTip
                                ((TextEdit)item).SuperTip = graduationBatchSuperToolTip;
                                //正则判断
                                ((TextEdit)item).Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.RegEx;
                                ((TextEdit)item).Properties.Mask.EditMask = BitsHelp.GetBitsToMask(XChipHDR[i].Bits, XChipHDR[i].Bit_Wide, XChipHDR.Where(c => c.NameType.ToLower().Contains(type) && c.ControlType == "0").Select(c => c.Bits).ToList());
                            }
                        }

                    }

                    xChip_HDR_Ae = new XChip_HDR_Ae(sPortTemp, aBll);
                    xChip_HDR_Ae.Dock = DockStyle.Fill;
                    xChip_HDR_Ae.Name = "xChip_HDR_Ae";
                    this.tabNavigationPage1.Controls.Add(xChip_HDR_Ae);
                    this.tabNavigationPage1.Name = "xChip_HDR_AePage";
                });
            });
        }

        private async void simpleButton1_Click(object sender, EventArgs e)
        {
            ratio_highlight.Text =(await GetRegister("ratio_highlight", hdrList)).ToString("X2");
            //ratio_lowlight.Text = GetRegister("ratio_lowlight", hdrList).ToString("X2");
            string Vals = string.Empty;
           // await ReadRegisterAsync(model.Address);
            Vals += (await ReadRegisterAsync(hdrList.Find(c => c.NameType.Contains("portion_highlight_h")).Address)).ToString("X2");
            Vals += (await ReadRegisterAsync(hdrList.Find(c => c.NameType.Contains("portion_highlight_l")).Address)).ToString("X2");
            portion_lighlight.Text = Vals;
        }

        private void simpleButton10_Click(object sender, EventArgs e)
        {

        }

        private void ratio_highlight_Leave(object sender, EventArgs e)
        {
            if (isRead) return;
            if (string.IsNullOrEmpty(ratio_highlight.Text)) return;
            if (hdrList.Count == 0)
            {
                if (null == addrDal)
                {
                    addrDal = new addressregisterManager();
                }
                hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
            }
            SetRegister("ratio_highlight", Convert.ToUInt32(ratio_highlight.Text, 16), hdrList);
        }

        private void ratio_highlight_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                ratio_highlight_Leave(sender, null);
            }
        }

        private async void portion_lighlight_Leave(object sender, EventArgs e)
        {
            if (isRead) return;
            if (null != sPortTemp || !IsUsbOpen || !m_open)
            {

                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (null == addrDal)
                {
                    addrDal = new addressregisterManager();
                }
                hdrList = addrDal.GetList(c => c.Classify.Contains("hdr"));
                if (hdrList.Exists(c => c.NameType.ToLower() == "portion_highlight".ToLower() + "_h"))
                {
                    var model = hdrList.Find(c => c.NameType.ToLower() == ("portion_highlight" + "_h").ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    await SetHDRRegister(model, Val);
                }
                if (hdrList.Exists(c => c.NameType.ToLower() == "portion_highlight".ToLower() + "_l"))
                {
                    var model = hdrList.Find(c => c.NameType.ToLower() == ("portion_highlight" + "_l").ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    await SetHDRRegister(model, Val);
                }
            }
        }

        private void portion_lighlight_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                portion_lighlight_Leave(sender, null);
            }
        }

        private void EnShowHide()
        {
            gamma_ratiolist0.Enabled = gamma_ratio_en.Checked;
            gamma_ratiolist1.Enabled = gamma_ratio_en.Checked;
            gamma_ratiolist2.Enabled = gamma_ratio_en.Checked;
            gamma_ratiolist3.Enabled = gamma_ratio_en.Checked;
            gamma_ratiolist4.Enabled = gamma_ratio_en.Checked;
            gamma_ratiolist5.Enabled = gamma_ratio_en.Checked;
            gamma_ratiolist6.Enabled = gamma_ratio_en.Checked;
            gamma_ratiolist7.Enabled = gamma_ratio_en.Checked;

            tome_mappinglist0.Enabled = tome_mapping_en.Checked;
            tome_mappinglist1.Enabled = tome_mapping_en.Checked;
            tome_mappinglist2.Enabled = tome_mapping_en.Checked;
            tome_mappinglist3.Enabled = tome_mapping_en.Checked;
            tome_mappinglist4.Enabled = tome_mapping_en.Checked;
            tome_mappinglist5.Enabled = tome_mapping_en.Checked;
            tome_mappinglist6.Enabled = tome_mapping_en.Checked;
            tome_mappinglist7.Enabled = tome_mapping_en.Checked;

            combine_preferLong_str.Enabled = combine_preferLong_en.Checked;

            weight_gainlist0.Enabled = weight_gain_en.Checked;
            weight_gainlist1.Enabled = weight_gain_en.Checked;
            weight_gainlist2.Enabled = weight_gain_en.Checked;
            weight_gainlist3.Enabled = weight_gain_en.Checked;
            weight_gainlist4.Enabled = weight_gain_en.Checked;
            weight_gainlist5.Enabled = weight_gain_en.Checked;
            weight_gainlist6.Enabled = weight_gain_en.Checked;
            weight_gainlist7.Enabled = weight_gain_en.Checked;
            weight_gainlist8.Enabled = weight_gain_en.Checked;

            weight_man.Enabled = weight_man_en.Checked;

            thresholdl.Enabled = weight_hds_en.Checked;
            thresholdh.Enabled = weight_hds_en.Checked;
            threshold_num.Enabled = weight_hds_en.Checked;

            combwt_man.Enabled = combwt_man_en.Checked;
            ratio_highlight.Enabled = !gamma_ratio_en.Checked;
        }

       
    }
}
